<template>
  <div class="animate__fadeInUp animate__animated animate__faster">
    <div class="name wrap">{{ lang.t('name') }}</div>
    <t-form ref="form" :data="formData" :rules="formRule" label-width="0" @submit="onSubmit">
      <t-form-item name="email">
          <t-input 
            :ref="el => input.email = el" 
            v-model="formData.email" 
            size="large" 
            placeholder="Email"
            @enter="input.password.focus()"
          >
          <template #prefix-icon>
            <t-icon name="user" />
          </template>
        </t-input>
      </t-form-item>

      <t-form-item name="password">
        <t-input
          :ref="el => input.password = el"
          v-model="formData.password"
          size="large"
          type="password"
          clearable
          placeholder="Password"
          @enter="form.submit()"
        >
          <template #prefix-icon>
            <t-icon name="lock-on" />
          </template>
        </t-input>
      </t-form-item>
      <t-form-item>
        <t-button size="large" :loading="loading" @click="form.submit()" block>
          {{ lang.t('login.user') }}
        </t-button>
      </t-form-item>
    </t-form>
    <div class="back" v-if="app.number()">
      <t-button size="large" theme="default" variant="base" shape="square" @click="emit('tabs')">
        <template #icon>
          <t-icon name="user" size="large" />
        </template>
      </t-button>
    </div>
  </div>
</template>

<script setup>
  import { ref, reactive, nextTick } from 'vue'
  import app from '@/app';
  import userStore from '@/store/user'
  
  const lang = app.lang.space('page.index')
  const emit = defineEmits(['tabs'])

  const input = reactive({})
  const loading = ref(false)
  const form = ref(null)
  const formData = ref({})
  const formRule = {
    email: [{ required: true, message: ' ', type: 'error' }],
    password: [{ required: true, message: ' ', type: 'error' }],
  }

  // 登陆 
  const onSubmit = ({ validateResult }) => {
    if (validateResult === true) {
      loading.value = true
      userStore.login(formData.value).then(res => {
        app.router.push('/user')
      }).catch(err => {
        app.message('error', 'message.error.' + err.message)
      }).finally(() => {
        loading.value = false
      })
    }
  }

  nextTick(() => {
    input.email.focus()
  })
</script>